package work2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Map;

public class WordCount {
	private String text="";
	private String inputFileName;
    private String outputFileName;
    private int chars;
    private int lines;
    private int words;
    private Map<String,Integer> wordsMap;
    
	public WordCount(String inputFileName,String outputFileName) throws IOException{
		this.inputFileName=inputFileName;
		this.outputFileName=outputFileName;
		input();
		count();
		output();
	}
	
	private void input() throws IOException {
	    File file=new File(inputFileName);
	    try {
	        FileInputStream in=new FileInputStream(file);
	        // size  为字串的长度 ，这里一次性读完
	        int size=in.available();
	        byte[] buffer=new byte[size];
	        in.read(buffer);
	        in.close();
	        this.text=new String(buffer,"UTF-8");
	    } catch (IOException e) {
	    	System.out.println("读文件错误！");
	        e.printStackTrace();
	    }
	    
	}
	
	private void count()
    {
        Lib lib = new Lib(text);
        chars = lib.countChar();
        lines = lib.countLine();
        words = lib.countWord();
        wordsMap = lib.getWordsTop10();
    }
	
	private void output() {
		
			
		PrintWriter output = null;
        try
        {
            output = new PrintWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(outputFileName),
                            "UTF-8"));    //输出设置编码为utf-8
            output.print("characters: " + chars + '\n');
            output.print("words: " + words + '\n');
            output.print("lines: " + lines + '\n');
            for (Map.Entry<String, Integer> entry : wordsMap.entrySet())
            {
                output.print(entry.getKey() + ": " + entry.getValue() + '\n');
            }
        }
        catch (Exception e)
        {
        	System.out.println("文件写出错！");
            System.out.print(e.getMessage());
        }
        finally
        {
            if(output != null)
                output.close();
        }
	}
	
	public static void main(String[] args) throws IOException {
        long time = System.currentTimeMillis();  //计算代码运行时间

        String inputFileName = args[0];
        String outputFileName = args[1];

        new WordCount(inputFileName, outputFileName);
        System.out.println("程序执行时间:"+(System.currentTimeMillis() - time) + "ms");
    }
}
